package com.bibrApp.difu.actvity.publist_jieru_mvp;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bibrApp.difu.DfApp;
import com.bibrApp.difu.R;
import com.bibrApp.difu.Response.FBInfoResBody;
import com.bibrApp.difu.Response.TradePawnInfo;
import com.bibrApp.difu.base.BaseActivity;
import com.bibrApp.difu.dialog.CustomDialog;
import com.bibrApp.difu.utils.BigdecimalUtils;
import com.bibrApp.difu.utils.CustomDialogUtils;
import com.bibrApp.difu.utils.ScreenUtils;
import com.bibrApp.difu.utils.ToastUtils;
import com.bibrApp.difu.utils.UIUtils;
import com.bibrApp.difu.widget.ExtraEditView;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 借入只能借usdt全是整数，抵押是选择BTC或者ETH
 * 到期利息=借贷金额*日利率*借贷期限
 */
public class PublistJieruActivity extends BaseActivity<PublistJieruPresenter> implements IPublistJieruView, TextWatcher {

    @BindView(R.id.tv_rule)
    TextView tvRule;
    @BindView(R.id.tv_xieyi)
    TextView tvXieyi;

    @BindView(R.id.et_day)
    ExtraEditView etDay;
    @BindView(R.id.et_dy)
    ExtraEditView etDy;
    @BindView(R.id.edittext)
    EditText etPrice;
    @BindView(R.id.bt_publish)
    Button btnPublish;
    @BindView(R.id.tv_lx)
    TextView tvLx;//到期利息
    @BindView(R.id.tv_bx)
    TextView tvBx;//本息
    @BindView(R.id.tv_coin_type)
    TextView tvCoinType;

    @BindView(R.id.higher_btc_tv)
    TextView tvHighBtc;//最高
    /**
     * 切换到ETH
     */
    @BindView(R.id.tv_lower)
    TextView tvLower;//最低
    @BindView(R.id.tv_higher_eth)
    TextView tvHighEth;//最高
    @BindView(R.id.et_lower)
    EditText etLow;//最底

    @BindView(R.id.tv_cycle)
    TextView tvCycleType;//借款周期
    @BindView(R.id.tv_info2)
    TextView tvDiya;//抵押
    @BindView(R.id.tv_drate)
    TextView tvDiyaNum;//预计抵押币种数


    @BindView(R.id.tv_yrate)
    TextView tvYearX;//年化收益

    private boolean isXieyiCheck;
    private PopupWindow popupWindow;
    private Context mContext;


    @Override
    protected void initPresenter() {
        presenter = new PublistJieruPresenter(this, this);
        presenter.init();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_publist_jieru;
    }


    @Override
    public void error(String msg) {

    }

    @Override
    public void success(String msg) {
        ToastUtils.ShowToast(mContext , msg);
        this.setResult(RESULT_OK);
        finish();
    }

    private FBInfoResBody fbInfo;

    @Override
    public void successOfGetFBInfo(FBInfoResBody fbInfoResBody) {
        fbInfo = fbInfoResBody;
    }

    private BigDecimal newPrice;

    @Override
    public void successOfGetBNewPrice(String price) {
        if (TextUtils.isEmpty(price)) {
            return;
        }
        newPrice = new BigDecimal(price);
    }

    private List<TradePawnInfo> tradePawnInfos;

    @Override
    public void successOfTradeBInfo(List<TradePawnInfo> tradePawnInfoList) {
        tradePawnInfos = tradePawnInfoList;
        if (tradePawnInfos != null && tradePawnInfos.size() > 0) {
            for (int i = 0; i < tradePawnInfos.size(); i++) {
                if (tradePawnInfos.get(i).getEunit().equalsIgnoreCase("BTC")) {
                    tradePawnInfo = tradePawnInfos.get(i);
                }
            }
        }
    }

    @Override
    public void initView() {
        mContext = this;
        tvRule.setText("您需要缴纳保证金才能发布");
        UIUtils.appendText(tvRule, "《保证金规则》", "#1D89E4");
        //输入日利率：点击日利率栏的+-符号的加减幅度为0.01%。在输入日利率后要显示出折和年华利率。
        //输入抵押率：点击抵押率栏的+-符号的加减幅度为10%。在输入了日利率抵押率后需要显示出预计抵押的资产数量。
        etDy.setCount(10);
        etDy.setExtra("%");
        etDy.setText("50%");
        etDy.setDecimal("0");
        etDy.setEtStr(50.0);

        etDay.setCount(0.01);
        etDay.setExtra("%");
        etDay.setDecimal("0.000");
        etDay.setEtStr(0.01);
        etDay.setText("0.010%");

        presenter.getBNewPrice(isEth ? "ETH" : "BTC");
        presenter.getBInfo();
        presenter.getTradeBInfo();

        etPrice.addTextChangedListener(this);
        etDay.setOnClickAddOrReduceListener(new ExtraEditView.OnClickAddOrReduceListener() {
            @Override
            public void onclickAR() {
                calculate();
                double dayx = Double.parseDouble(etDay.getEtStr());
                double yearx = dayx * 365 * 100;
                tvYearX.setText(BigdecimalUtils.format2Str(yearx, 3) + "%");
            }
        });
        etDy.setOnClickAddOrReduceListener(new ExtraEditView.OnClickAddOrReduceListener() {
            @Override
            public void onclickAR() {
                calculate();
            }
        });
    }

    @OnClick(R.id.tv_rule)
    public void ruleClick() {

    }

    @OnClick(R.id.tv_xieyi)
    public void xieyiClick() {
        isXieyiCheck = !isXieyiCheck;
        UIUtils.setDrawableLeft(tvXieyi, isXieyiCheck ? R.mipmap.icon_check : R.mipmap.icon_nocheck);
        typeChange();
    }

    @OnClick(R.id.bt_xieyi)
    public void xieyi2Click() {

    }

    @OnClick(R.id.bt_publish)
    public void publishClick() {
        /**
         * 发布借入
         legalCoinId	String	是	法币币种ID
         pawnCoinId	String	是	抵押币币种ID
         legalQuantity	String	是	法币数量ID
         cycle	int	是	周期
         pawnRate	Bigdecimal	是	抵押率
         legalDailyRate	Bigdecimal	是	日利率
         totalInterest	Bigdecimal	是	总利息
         lowPrice	Bigdecimal	是	最低价
         highPrice	Bigdecimal	是	最高价
         tradePassword	String	是	交易密码
         */

        if (tradePawnInfo == null || fbInfo == null) {
            return;
        }
        showInputTradePwdDialog();

    }

    /**
     * 资金安全码弹窗
     */
    private void showInputTradePwdDialog() {
        CustomDialogUtils.showEditDialog(mContext, "请输入资金安全吗", "确认", new CustomDialog.OnEditClickListener() {
            @Override
            public void onPositiveClick(View view, String pwd) {
                DfApp dfApp = (DfApp) getApplication();
                String priceStr = etPrice.getText().toString().replace(" ", "");
                String lowStr = etLow.getText().toString().replace(" ", "");

                if (!TextUtils.isEmpty(pwd) && pwd.length() >= 6) {
                    presenter.publishAd(fbInfo.getId(), tradePawnInfo.getId(), priceStr, cycle, etDy.getEtStr(), etDay.getEtStr(), tvLx.getText().toString(), isEth ? lowStr : priceStr, "10000000", pwd);
                } else {
                    ToastUtils.ShowToast(mContext, "资金安全码错误");
                }
            }
        });
    }

    private boolean isEth;
    private TradePawnInfo tradePawnInfo;//抵押币种信息BTC或ETH

    @OnClick(R.id.tv_coin_type)
    public void coinTypeClick() {
        View layout = View.inflate(this, R.layout.pop_coin_type, null);

        layout.findViewById(R.id.tv_all).setVisibility(View.GONE);
        layout.findViewById(R.id.tv_usdt).setVisibility(View.GONE);
        layout.findViewById(R.id.tv_btc).setOnClickListener(view -> {
            isEth = false;
            tvCoinType.setText("BTC");
            updataView();
            popupWindow.dismiss();
            if (tradePawnInfos != null && tradePawnInfos.size() > 0) {
                for (int i = 0; i < tradePawnInfos.size(); i++) {
                    if (tradePawnInfos.get(i).getEunit().equalsIgnoreCase("BTC")) {
                        tradePawnInfo = tradePawnInfos.get(i);
                    }
                }
            }
            presenter.getBNewPrice(isEth ? "ETH" : "BTC");
        });
        layout.findViewById(R.id.tv_eth).setOnClickListener(view -> {
            isEth = true;
            tvCoinType.setText("ETH");
            updataView();
            popupWindow.dismiss();
            if (tradePawnInfos != null && tradePawnInfos.size() > 0) {
                for (int i = 0; i < tradePawnInfos.size(); i++) {
                    if (tradePawnInfos.get(i).getEunit().equalsIgnoreCase("ETH")) {
                        tradePawnInfo = tradePawnInfos.get(i);
                    }
                }
            }
            presenter.getBNewPrice(isEth ? "ETH" : "BTC");
        });

        popupWindow = new PopupWindow(layout, UIUtils.dpToPixels(this, 65), -2, true);
        popupWindow.setFocusable(true);

        popupWindow.setOutsideTouchable(true);
        ScreenUtils.setBackgroundAlpha(mContext, 0.5f);
        popupWindow.showAsDropDown(tvCoinType, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ScreenUtils.setBackgroundAlpha(mContext, 1.0f);
            }
        });
    }

    @OnClick(R.id.bt_back)
    public void clickBack() {
        finish();
    }

    /**
     * 根据选择的币种改变ui
     */
    private void updataView() {
        tvHighEth.setVisibility(isEth ? View.VISIBLE : View.GONE);
        tvLower.setVisibility(isEth ? View.VISIBLE : View.GONE);
        etLow.setVisibility(isEth ? View.VISIBLE : View.GONE);
        tvHighBtc.setVisibility(isEth ? View.GONE : View.VISIBLE);
        if (isEth) {
            tvDiya.setText("预计抵押(ETH)");
        } else {
            tvDiya.setText("预计抵押(BTC)");
        }

    }

    private int cycle = 30;

    @OnClick(R.id.tv_cycle)
    public void clickCycle() {
        View layout = View.inflate(this, R.layout.pop_cycle_type, null);


        layout.findViewById(R.id.tv_7).setOnClickListener(view -> {
            setCycleType(7);
        });
        layout.findViewById(R.id.tv_15).setOnClickListener(view -> {
            setCycleType(15);
        });
        layout.findViewById(R.id.tv_30).setOnClickListener(view -> {
            setCycleType(30);
        });

        layout.findViewById(R.id.tv_60).setOnClickListener(view -> {
            setCycleType(60);
        });

        layout.findViewById(R.id.tv_120).setOnClickListener(view -> {
            setCycleType(120);
        });

        layout.findViewById(R.id.tv_180).setOnClickListener(view -> {
            setCycleType(180);
        });

        popupWindow = new PopupWindow(layout, UIUtils.dpToPixels(this, 128), -2, true);
        popupWindow.setFocusable(true);
        ScreenUtils.setBackgroundAlpha(mContext, 0.5f);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAsDropDown(tvCycleType, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ScreenUtils.setBackgroundAlpha(mContext, 1.0f);
            }
        });
    }

    private void setCycleType(int c) {
        cycle = c;
        tvCycleType.setText(c + "天");
        calculate();
        popupWindow.dismiss();
        ScreenUtils.setBackgroundAlpha(mContext, 1.0f);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    //最多8位小数
    @Override
    public void afterTextChanged(Editable s) {
        typeChange();
        calculate();
    }

    /**
     * 计算
     * 预计抵押=借贷金额/抵押率/实时币价
     */
    private void calculate() {
        String priceStr = etPrice.getText().toString().replace(" ", "");
        if (TextUtils.isEmpty(priceStr) || newPrice == null) {
            return;
        }
        BigDecimal priceBD = BigdecimalUtils.getBigDecimalPrice(priceStr, BigdecimalUtils.getPointNum(priceStr));
        BigDecimal dayRxBD = BigdecimalUtils.getBigDecimalPrice(etDay.getEtStr(), 5);
        BigDecimal dyBD = BigdecimalUtils.getBigDecimalPrice(etDy.getEtStr(), 5);
        BigDecimal dayLxBD = BigdecimalUtils.getBigDecimalPrice(String.valueOf(priceBD.multiply(new BigDecimal(cycle)).multiply(dayRxBD)), 8);
        String lxStr = String.valueOf(BigdecimalUtils.getBigDecimalPrice(String.valueOf(priceBD.multiply(new BigDecimal(cycle)).multiply(dayRxBD)), 8));
        tvLx.setText(lxStr);
        tvBx.setText(String.valueOf(priceBD.add(dayLxBD)));
        if (dyBD.compareTo(new BigDecimal(0)) > 0) {
            tvDiyaNum.setText(String.valueOf(BigdecimalUtils.getBigDecimalPrice(String.valueOf(priceBD.divide(dyBD, 8, RoundingMode.DOWN).divide(newPrice, 8, RoundingMode.DOWN)), 8)));
        }
    }

    /**
     * 发布借入按钮状态刷新
     */
    private void typeChange() {
        if (isEth) {
            if (isXieyiCheck && !TextUtils.isEmpty(etPrice.getText().toString().replaceAll(" ", "")) && !TextUtils.isEmpty(etLow.getText().toString().replaceAll(" ", ""))) {
                btnPublish.setClickable(true);
                btnPublish.setEnabled(true);
            } else {
                btnPublish.setClickable(false);
                btnPublish.setEnabled(false);
            }
        } else {
            if (isXieyiCheck && !TextUtils.isEmpty(etPrice.getText().toString().replaceAll(" ", ""))) {
                btnPublish.setClickable(true);
                btnPublish.setEnabled(true);
            } else {
                btnPublish.setClickable(false);
                btnPublish.setEnabled(false);
            }
        }
    }
}
